#!/bin/bash
# 项目初始化脚本（Linux/Mac）

echo "========================================"
echo "南昌旅游路线规划系统 - 项目初始化"
echo "========================================"
echo ""

# 检查Python
echo "[1/6] 检查Python环境..."
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到Python3，请先安装Python 3.8+"
    exit 1
fi
python3 --version
echo ""

# 检查Node.js
echo "[2/6] 检查Node.js环境..."
if ! command -v node &> /dev/null; then
    echo "警告: 未找到Node.js，前端功能可能无法使用"
else
    node --version
fi
echo ""

# 检查Redis
echo "[3/6] 检查Redis服务..."
python3 -c "import redis; r = redis.Redis(host='127.0.0.1', port=6379, db=0); r.ping(); print('Redis连接正常')" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "警告: Redis未运行，Celery功能将无法使用"
    echo "请启动Redis: redis-server"
else
    echo "Redis连接正常"
fi
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# 安装后端依赖
echo "[4/6] 安装后端依赖..."
cd "$PROJECT_DIR/backend"
if [ ! -d "venv" ]; then
    echo "创建虚拟环境..."
    python3 -m venv venv
fi
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
if [ $? -ne 0 ]; then
    echo "错误: 依赖安装失败"
    exit 1
fi
echo "后端依赖安装完成"
echo ""

# 数据库迁移
echo "[5/6] 执行数据库迁移..."
python manage.py migrate
if [ $? -ne 0 ]; then
    echo "警告: 数据库迁移失败，请检查数据库配置"
fi
echo ""

# 创建超级用户（可选）
echo "[6/6] 创建超级用户..."
read -p "是否创建超级用户？(y/n): " create_superuser
if [ "$create_superuser" = "y" ] || [ "$create_superuser" = "Y" ]; then
    python manage.py createsuperuser
fi
echo ""

# 安装前端依赖
cd "$PROJECT_DIR/frontend"
if [ -f "package.json" ]; then
    echo "安装前端依赖..."
    npm install
    if [ $? -ne 0 ]; then
        echo "警告: 前端依赖安装失败"
    else
        echo "前端依赖安装完成"
    fi
fi

echo ""
echo "========================================"
echo "项目初始化完成！"
echo "========================================"
echo ""
echo "下一步："
echo "1. 启动后端: cd backend && source venv/bin/activate && python manage.py runserver"
echo "2. 启动前端: cd frontend && npm run serve"
echo "3. 启动Celery: cd backend && ./scripts/start_celery.sh"
echo ""

